package io.nutz.nutzsite.module.exam.services;

import io.nutz.nutzsite.common.base.Service;
import io.nutz.nutzsite.common.utils.StringUtils;
import io.nutz.nutzsite.common.utils.excel.ImportExcel;
import io.nutz.nutzsite.module.exam.models.Question;

import java.util.List;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.upload.TempFile;

import com.google.protobuf.ServiceException;
/**
 * 题目 服务层实现
 * 
 * @author lrw
 * @date 2020-04-08
 */
@IocBean(args = {"refer:dao"})
public class QuestionService extends Service<Question> {
	private static final Log log = Logs.get();
	public QuestionService(Dao dao) {
		super(dao);
	}
	/**
	 * 导入数据
	 * @param file 导入的数据文件
	 * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
	 * @throws ServiceException 
	 */
	public String importData(TempFile file) throws ServiceException {
		if (file == null){
			throw new ServiceException("请选择导入的数据文件！");
		}
		int successNum = 2; int failureNum=0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		try{
			ImportExcel ei = new ImportExcel(file, 2, 0);
			List<Question> list = ei.getDataList(Question.class);
			log.debug("\r\n找到即将导入的题目数: "+list.size());
			for (Question question : list) {
				try{
					question.setName(StringUtils.HtmlEscape( question.getName()));
					question.setAnsA(StringUtils.HtmlEscape( question.getAnsA()));
					question.setAnsB(StringUtils.HtmlEscape( question.getAnsB()));
					if(Strings.isNotBlank(question.getAnsC()))
					question.setAnsC(StringUtils.HtmlEscape( question.getAnsC()));
					if(Strings.isNotBlank(question.getAnsD()))
					question.setAnsD(StringUtils.HtmlEscape( question.getAnsD()));
					if(Strings.isNotBlank(question.getQnote()))
					question.setQnote(StringUtils.HtmlEscape( question.getQnote()));
					this.insert(question);
					successNum++;
					successMsg.append("<br/>" + successNum  + " 导入成功");
				} catch (Exception e) {
					successNum++;failureNum++;
					String msg = "<br/>" + successNum +  " 导入失败：";
					if (e instanceof ConstraintViolationException){
						ConstraintViolationException cve = (ConstraintViolationException)e;
						for (ConstraintViolation<?> violation : cve.getConstraintViolations()) {
							msg += violation.getMessage() + " ("+violation.getPropertyPath()+")";
						}
					}else{
						msg += e.getMessage();
					}
					failureMsg.append(msg);
				}
			}
		} catch (Exception e) {
			failureMsg.append(e.getMessage());
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new ServiceException(failureMsg.toString());
		}else{
			successMsg.insert(0, "恭喜您，数据已全部导入成功！");
		}
		return successMsg.toString();
	}
}
